package com.api.aop

import com.api.config.APIConfig
import com.api.util.TokenUtils
import com.base.db.mysql.MySQLService
import com.base.db.mysql.admin_getRoleJkidsByUid
import com.base.utils.splitWithEmpty
import com.yfree.config.YConfig
import com.yfree.global.YController
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.context.event.ApplicationStartedEvent
import org.springframework.context.ApplicationListener
import org.springframework.stereotype.Component
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


@Component
class ApplicationStartAop(
        val mysqlService: MySQLService,
) : YController(), ApplicationListener<ApplicationStartedEvent> {
    @Value("\${spring.profiles.active}")
    private lateinit var active: String

    override fun onApplicationEvent(event: ApplicationStartedEvent) {
        YConfig.DEBUG = active != "release"
        YConfig.Request.filterCallBack = filterCallBack@{ request: HttpServletRequest, response: HttpServletResponse, handle: Any ->
            if (YConfig.DEBUG && request.method.toUpperCase() == "GET") return@filterCallBack true
            when {
                request.getHeader("admin-sign") != null -> {
                    // body
                    val jkid = request.getParameter("jkid")
                    val jkparam = request.getParameter("jkparam")
                    if (jkid.isNullOrEmpty()) {
                        response.writer.println(yResult(code = -1000, message = "接口编号缺失"))
                        return@filterCallBack false
                    }
                    // header
                    val admin_platform_version = request.getHeader("admin-platform-version")
                    val admin_sign = request.getHeader("admin-sign")
                    var accessToken: String? = null
                    var refreshToken: String? = null
                    var uid: String? = null
                    if (admin_sign != null && admin_sign.isNotBlank() && admin_sign.contains("|")) {
                        accessToken = admin_sign.split("|")[0]
                        refreshToken = admin_sign.split("|")[1]
                        uid = TokenUtils.decode(accessToken)
                    }
                    if (!APIConfig.noVerifyJkids.contains(jkid)) {
                        if (admin_platform_version.isNullOrEmpty() || admin_sign.isNullOrEmpty()) {
                            response.writer.println(yResult(code = -1000, message = "签名参数缺失"))
                            return@filterCallBack false
                        }
                        if (uid.isNullOrEmpty()) {
                            response.writer.println(yResult(code = -1000, message = "验证签名失败"))
                            return@filterCallBack false
                        }
                    }
                    if (admin_sign.isNotEmpty()) {
                        val jkids = mysqlService.admin_getRoleJkidsByUid(uid)
                        if (jkids.isNullOrBlank()) {
                            response.writer.println(yResult(code = -1000, message = "角色校验失败1"))
                            return@filterCallBack false
                        }
                        if (jkids != "*")
                            if (jkids.startsWith("*-")) {
                                if ((jkids.split("*-").last()).split(",").contains(jkid)) {
                                    response.writer.println(yResult(code = -1000, message = "角色校验失败2"))
                                    return@filterCallBack false
                                }
                            } else {
                                if (!jkids.splitWithEmpty(",").contains(jkid)) {
                                    response.writer.println(yResult(code = -1000, message = "角色校验失败3"))
                                    return@filterCallBack false
                                }
                            }
                    }
                    request.setAttribute(APIConfig.attrKey, mapOf(
                            "admin_platform_version" to admin_platform_version,
                            "admin_sign" to admin_sign,
                            "uid" to uid,
                            "accessToken" to accessToken,
                            "refreshToken" to refreshToken,
                    ))
                    return@filterCallBack true
                }

                request.getHeader("app-sign") != null -> {
                    // body
                    val jkid = request.getParameter("jkid")
                    val jkparam = request.getParameter("jkparam")
                    if (jkid.isNullOrEmpty()) {
                        response.writer.println(yResult(code = -1001, message = "接口编号缺失"))
                        return@filterCallBack false
                    }
                    // header
                    val app_platform_isweb = request.getHeader("app-platform-isweb")
                    val app_platform_system = request.getHeader("app-platform-system")
                    val app_platform_version = request.getHeader("app-platform-version")
                    val app_locale = request.getHeader("app-locale") ?: "zh"
                    val app_version = request.getHeader("app-version")
                    val app_sign = request.getHeader("app-sign")
                    var accessToken: String? = null
                    var refreshToken: String? = null
                    var uid: String? = null
                    if (app_sign != null && app_sign.isNotBlank() && app_sign.contains("|")) {
                        accessToken = app_sign.split("|")[0]
                        refreshToken = app_sign.split("|")[1]
                        uid = TokenUtils.decode(accessToken)
                        if (jkid != APIConfig.refreshTokenJkid && uid == null) {
                            response.writer.println(yResult(code = -1001, message = "验证签名过期"))
                            return@filterCallBack false
                        }
                    }
                    if (!APIConfig.noVerifyJkids.contains(jkid)) {
                        if (app_platform_isweb.isNullOrEmpty() || app_platform_system.isNullOrEmpty() || app_platform_version.isNullOrEmpty() || app_version.isNullOrEmpty() || app_sign.isNullOrEmpty()) {
                            response.writer.println(yResult(code = -1001, message = "签名参数缺失"))
                            return@filterCallBack false
                        }
                        if (uid.isNullOrEmpty()) {
                            response.writer.println(yResult(code = -1001, message = "验证签名失败"))
                            return@filterCallBack false
                        }
                    }
                    request.setAttribute(APIConfig.attrKey, mapOf(
                            "app_platform_isweb" to app_platform_isweb,
                            "app_platform_system" to app_platform_system,
                            "app_platform_version" to app_platform_version,
                            "app_locale" to app_locale,
                            "app_version" to app_version,
                            "app_sign" to app_sign,
                            "uid" to uid,
                            "accessToken" to accessToken,
                            "refreshToken" to refreshToken,
                    ))
                    return@filterCallBack true
                }

                else -> {
                    response.writer.println(yResult(code = -1001, message = "目标不存在"))
                    return@filterCallBack false
                }
            }

        }
    }
}
